package com.glela.platform.service.impl;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.glela.common.util.Config;
import com.glela.common.util.HttpUtil;
import com.glela.platform.constant.ErrorEnum;
import com.glela.platform.mapper.ChangeProcessLogMapper;
import com.glela.platform.mapper.TalentJobMapper;
import com.glela.platform.mapper.UserInfoMapper;
import com.glela.platform.mapper.UserMapper;
import com.glela.platform.model.ChangeProcessLog;
import com.glela.platform.model.TalentJob;
import com.glela.platform.model.User;
import com.glela.platform.model.UserInfo;
import com.glela.platform.model.response.ResponseBaseModel;
import com.glela.platform.model.response.higou.HigouApi;
import com.glela.platform.model.response.higou.HigouApiTalentJob;
import com.glela.platform.service.TalentJobSerice;

/********************************************
	 * 
	 * <dl>
	 * <dt>讲师 服务类</dt>
	 * </dl>
	 * @author gwq
	 * @date 2017年7月29日 13:44:05
	 * 
	 ********************************************/
@Service("talentJobSerice")
public class TalentJobSericeImpl implements TalentJobSerice {
	private static Logger LOGGER = LoggerFactory.getLogger(TalentJobSericeImpl.class);
	
	@Autowired
	private ChangeProcessLogMapper changeProcessLogMapper;
	@Autowired
	private TalentJobMapper talentJobMapper;
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private UserInfoMapper userInfoMapper;

	@Override
	public TalentJob selectTalentJobByPersonId(String persionId) {
		return talentJobMapper.selectTalentJobByPersonId(persionId);
	}

	@Override
	public TalentJob getTalentJobByUserId(long userId) {
		// TODO Auto-generated method stub
		return talentJobMapper.selectTalentJobByUserId(userId);
	}

	@Override
	public ResponseEntity<?> addTalentJobByUserId(long userId, String userName, String password) {
		try {
			//校验认证用户有效性
			User u=userMapper.selectByPrimaryKey(userId);
			if(u==null){
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20113), HttpStatus.OK);
			} else if (u.getRoleId() == 7) {//如果已经是讲师，提示重复
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C42001), HttpStatus.OK);
			}
			//不是讲师，从平达后台验证讲师信息
			StringBuilder URL = new StringBuilder();
			// URL.append("http://180.166.239.106:19900/pingda/higou/getuser?userName=").append(userName);
			URL.append(Config.getString("xz.getUser")).append("?").append("userName=").append(userName);
			HigouApi _result_data = null;
			try {
				String json = HttpUtil.doGet(URL.toString());
				_result_data = JSONObject.parseObject(json, HigouApi.class);
			} catch (Exception e) {
				LOGGER.warn("讲师认证-调用接口失败：{}-{}-{},{}", userId, userName, password, e.getMessage());
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20147, "讲师认证服务暂停，请稍候再试"), HttpStatus.OK);
			}
			if (_result_data.isResult() == false) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20147, _result_data.getMessage()), HttpStatus.OK);
			}
//			JSONObject jobj = JSONObject.parseObject(json);
			// 第二层json
//			String obj = jobj.get("data").toString();
			// JSONArray weatherJson = JSONObject.parseArray(obj);
			// JSONObject weather_data = weatherJson.getJSONObject(0);

			//校验讲师密码
			HigouApiTalentJob vo = _result_data.getData();
			if (!vo.getPassword().equals(password)) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20106, "讲师帐号或密码错误"), HttpStatus.OK);
			}
			int d = vo.isDimission() ? 1 : 0;
			TalentJob JiangShi=talentJobMapper.selectTalentJobByUserId(userId); 
			// 校验是否已经认证过
			if (JiangShi!=null) {//该用户已绑定的讲师信息
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C42001), HttpStatus.OK);
//				//开始记录日志
//				ChangeProcessLog Log=new ChangeProcessLog();
//				Log.setDescription("删除讲师信息");
//				Log.setMethod("TalentJobSericeImpl.addTalentJobByUserId");
//				Log.setPrimaryID(String.valueOf(JiangShi.getId()));
//				Log.setTableName("yg_user.talent_job");
//				Log.getBeforeMap().put("Talent",JiangShi);
//				changeProcessLogMapper.insert(Log);
//				// 添加讲师信息之前删除掉用户确认数据正确
//				talentJobMapper.deleteTalentByUserId(userId);
			}

			/*事务开始*/
			// 校验该讲师有没有被认证
			TalentJob talentJob;
			try {
				talentJob = this.talentJobMapper.selectTalentJobByJobNo(vo.getJobNo());
			} catch (Exception e) {
				LOGGER.error("{}-{}-{}根据讲师查询认证记录失败：{}", userId, userName, password, e.getMessage());
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C42002), HttpStatus.OK);
			}
			if (talentJob != null) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C42002), HttpStatus.OK);
			}

			//讲师未被认证过，记录认证管理
			talentJobMapper.insertTalentJobByUserId(vo.getJobNo(), vo.getLeader(), vo.getLeaderName(), vo.getName(), password, vo.getBranchId(), vo.getBranchName(), d, userId);
			//记录日志
			ChangeProcessLog Log=new ChangeProcessLog();
			Log.setDescription("添加讲师信息");
			Log.setMethod("TalentJobSericeImpl.addTalentJobByUserId");
			Log.setPrimaryID("");
			Log.setTableName("yg_user.talent_job");
			Log.getAfterMap().put("TalentJob",vo);
			Log.getAfterMap().put("userId",userId);
			changeProcessLogMapper.insert(Log);
			
			//记录日志
			Log=new ChangeProcessLog();
			Log.setDescription("用户信息变更");
			Log.setMethod("TalentJobSericeImpl.addTalentJobByUserId");
			Log.setPrimaryID(String.valueOf(userId));
			Log.setTableName("yg_user.c_user");
			Log.getBeforeMap().put("role",u.getRoleId());
			Log.getBeforeMap().put("RecommendFrom",u.getRecommendFrom());
			Log.getBeforeMap().put("TalentTeacher",u.getTalentTeacher());

			UserInfo userInfo = userInfoMapper.selectByUserId(userId);
			
			Log.getAfterMap().put("role",7);
			Log.getAfterMap().put("RecommendFrom",userInfo.getPersionId());
			Log.getAfterMap().put("TalentTeacher","");
			changeProcessLogMapper.insert(Log);
			
			// 用户变成讲师
			userMapper.becomeTalentTeacherById(userId,userInfo.getPersionId(),"");
			userMapper.updateUserEmpiricValue(userId, 10);
		} catch (Exception e) {
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
		return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
	}

	@Override
	public ResponseEntity<?> chengeTalentJobByNo(TalentJob talentJob) {
		// TODO Auto-generated method stub
		TalentJob tlentJob = talentJobMapper.selectTalentJobByJobNo(talentJob.getJobNo());
		if (tlentJob == null) {
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20172), HttpStatus.OK);
		}
		if (talentJob.getBranchId() == null && talentJob.getBranchName() == null && talentJob.getDimission() == null
				&& talentJob.getLeader() == null && talentJob.getLeaderName() == null && talentJob.getName() == null
				&& talentJob.getPassword() == null) {
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
		}
		int i = talentJobMapper.updateTalentJobByNo(talentJob);
		if (i == 0) {
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
		return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
	}

}
